package com.c2rusthub.service.controller;

import com.c2rusthub.service.model.User;
import com.c2rusthub.service.response.Response;
import com.c2rusthub.service.response.StatusCodeEnum;
import com.c2rusthub.service.utils.UserCacheUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName BaseController
 * @Description
 * @Author zhaozhiju
 * @Date 2024/12/2 3:02 PM
 * @Version V1.0
 */
public abstract class BaseController {

    protected final Logger LOG = LoggerFactory.getLogger(getClass());

    //---------------- 成功 --------------------
    protected ResponseEntity<Response> success() {
        return setResponse(StatusCodeEnum.OK, StatusCodeEnum.OK.msg(), null);
    }

    protected ResponseEntity<Response> success(Object data) {
        return setResponse(StatusCodeEnum.OK, StatusCodeEnum.OK.msg(), data);
    }

    protected ResponseEntity<Response> success(String msg, Object data) {
        return setResponse(StatusCodeEnum.OK, msg, data);
    }

    //---------------- 失败 --------------------
    protected ResponseEntity<Response> failure() {
        return setResponse(StatusCodeEnum.FAIL, StatusCodeEnum.FAIL.msg(), null);
    }

    protected ResponseEntity<Response> failure(String msg) {
        return setResponse(StatusCodeEnum.FAIL, msg, null);
    }

    protected ResponseEntity<Response> failure(StatusCodeEnum statusCode) {
        return setResponse(statusCode, statusCode.msg(), null);
    }

    protected ResponseEntity<Response> failure(StatusCodeEnum statusCode, String msg) {
        return setResponse(statusCode, msg, null);
    }

    /**
     * 响应报文
     *
     * @param statusCode 状态码
     * @param msg        消息
     * @param data       数据
     * @return 响应实体
     */
    private ResponseEntity<Response> setResponse(StatusCodeEnum statusCode, String msg, Object data) {
        return ResponseEntity.ok(new Response(statusCode.code(), msg, data));
    }

    /**
     * 根据 token 获取用户信息
     *
     * @param request 请求对象
     * @return 用户信息
     */
    protected User getUserFromToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");  // 从请求头获取token
        if (token == null || token.isEmpty()) {
            throw new RuntimeException("Token 不存在");
        }

        User user = UserCacheUtil.getUserFromCache(token);
        if (user == null) {
            throw new RuntimeException("用户未登录或Token无效");
        }

        return user;  // 返回用户信息
    }

    protected String getToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");  // 从请求头获取token
        if (token == null || token.isEmpty()) {
            throw new RuntimeException("Token 不存在");
        }

        return token;  // 返回用户信息
    }

}
